<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>weakSet案例</title>
    <style>
        *{
            padding: 0;
            margin: 0;
        }
        body{
            padding: 200px;
        }
        ul{
            list-style: none;
            display: flex;
            width: 200px;
            flex-direction: column;
        }
        li{
            height: 30px;
            border: solid 2px #e67e22;
            margin-bottom: 10px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding-left: 10px;
            color: #333333;
            transition: 1s;
        }
        a{
            border-radius: 3px;
            width: 20px;
            height: 20px;
            text-decoration: none;
            text-align: center;
            background: #16a085;
            color: white;
            cursor: pointer;
            display: flex;
            justify-content: center;
            align-items: center;
            margin-right: 5px;
        }
        .remove{
            border: solid 2px #eeeeee;
            opacity: 0.8;
            color: #eeeeee;
        }
        .remove a{
            background: #eeeeee;
        }
    </style>
</head>
<body>
    <ul>
        <li>houduren.com <a href="javascript:;">x</a></li>
        <li>hdcms.com <a href="javascript:;">x</a></li>
        <li>houdunwang.com <a href="javascript:;">x</a></li>
    </ul>
</body>
</html>


<script>
    class ToDo{
        //声明构造函数
        constructor(){
            this.run();
        }
        //运行入口文件
        run(){
            //得到所有的li对象
            this.items = document.querySelectorAll('ul > li');
            //定义一个wakeSet
            this.lists = new WeakSet();
            //将item中的数据给lists
            this.record()
            //给每个元素添加事件
            this.addEvent()
        }

        //初始化数据
        record(){
            this.items.forEach(item => {
                this.lists.add(item)
            });
        }

        //给元素添加事件
        addEvent(){
            let that = this;
            this.items.forEach(item => {
                item.querySelector('a').addEventListener('click',function(event){
                    //如果wackSet中存在这个数据，就进行删除操作，然后添加上remove类，否则的话，就添加这个元素，然后进行分类移除
                    // console.log(event.target)//event.target  代表的是当前作用的元素 这里指代的是a
                    let parentElement = event.target.parentElement;
                    if(!!that.lists.has(parentElement)){
                        parentElement.classList.add('remove');
                        that.lists.delete(parentElement);
                    }else{
                        parentElement.classList.remove('remove');
                        that.lists.add(parentElement)
                    }                    
                });
            });
        }

    }

    new ToDo();

</script>